package SymbolTable.SymbolTable;

/*
    用链表实现符号表，符号表（存键值对）
 */
public class SymbolTable<K, V> {

    private class Node<K, V> {
        K key;
        V value;
        Node<K, V> next;

        public Node(K key, V value, Node<K, V> next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

    }

    private Node<K, V> head;
    private int N;

    public SymbolTable() {
        head = new Node<>(null, null, null);
        N = 0;
    }

    public int size() {
        return N;
    }

    public V get(K key) {
        Node<K, V> current = head;
        while (current.next != null) {
            current=current.next;
            if (current.key.equals(key)) {
                return current.value;
            }
        }
        return null;
    }

    public void put(K key, V value) {
        //if table already has this key, we should use the new value replace the old value
        //just replace, size keep
        Node<K, V> n = head;
        while (n.next != null) {
            n = n.next;
            if (n.equals(key)) {
                n.value = value;
                return;
            }
        }
        //else we should create new node, size + 1
        //头插法
        Node<K, V> newNode = new Node<>(key, value, null);
        Node<K, V> oldFirst = head.next;
        newNode.next = oldFirst;
        head.next = newNode;
        N++;
    }

    public V delete(K key) {
        Node<K, V> n = head;
        while (n.next != null) {
            if (n.next.key.equals(key)) {
                Node<K, V> node = n.next;
                n.next = n.next.next;
                N--;
                return node.value;
            }
            n = n.next;
        }
        return null;
    }
}
